/*
 * Copyright (c) 2020 Mike Penz
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mikepenz.iconics.typeface;

import ohos.app.Context;

import com.mikepenz.iconics.typeface.utils.IconicsPreconditions;

import java.util.HashMap;

/**
 * @author pa.gulko zTrap (02.05.2020)
 */
public class IconicsHolder {
    private static final HashMap<String, ITypeface> FONTS = new HashMap<>();
    private static final IconicsHolder INSTANCE = new IconicsHolder();
    private Context context;

    private IconicsHolder() {
    }

    public static IconicsHolder getInstance() {
        return INSTANCE;
    }

    /**
     * 获取上下文
     *
     * @return 上下文
     * @throws RuntimeException 异常
     */
    public Context getApplicationContext() {
        if (context == null) {
            String message = "A 'Iconics.init(context)' has to happen first. Call from your application."
                + " Usually this happens via an 'IconicsDrawable' usage.";
            throw new RuntimeException(message);
        } else {
            return context;
        }
    }

    /**
     * 设置上下文
     *
     * @param context 上下文
     */
    public void setContext(Context context) {
        if (this.context == null) {
            this.context = context.getApplicationContext();
        }
    }

    /**
     * 注册字体
     *
     * @param font 字体
     * @return 是否注册成功
     */
    public static boolean registerFont(ITypeface font) {
        FONTS.put(font.getMappingPrefix(), validate(font));
        return true;
    }

    private static ITypeface validate(ITypeface font) {
        IconicsPreconditions.getInstance().checkMappingPrefix(font.getMappingPrefix());
        return font;
    }

    public static HashMap<String, ITypeface> getFonts() {
        return FONTS;
    }
}
